/**
 * 画图层
 */
define([ 'createjs', 'async', './ToolRedoUndo','eventEmitter','../Util','./Pager/main','./PencilData'], function(createjs, async, ToolRedoUndo, EventEmitter, util,Pager,PencilData) {
	var Layer = function() {
		//常用标识
		this.canvasEle = false;
		this.container = false;
		this.imgObj = false;

		this.canvasWidth = false;
		this.canvasHeight = false;

		this.toolRedoUndo = new ToolRedoUndo();
		this.pencilData = new PencilData();
		
		//私有标识
		this._pagers = [];
		this._currentPage = 0;
		
		
		/**
		 * 初始化方法
		 * @param {String} canvasId 画板Id
		 * @param {Object} imgObj 图片对象属性有img,fileOrPpt
		 */
		this.init = function(canvasId, imgObj) {
			this.canvasEle = document.getElementById(canvasId);
			this.canvasWidth = this.canvasEle.width;
			this.canvasHeight = this.canvasEle.height;

			this.container = new createjs.Stage(canvasId);
			this._pagers[0] = new Pager(this.canvasWidth,this.canvasHeight,this.pencilData);
			this._pagers[0].init();
			this.container.addChild(this._pagers[0].container);
			
			this.imgObj = imgObj;
			console.log('图层初始化');
			
//			this.testShape = new createjs.Shape();
//		this.testShape.graphics.beginFill("#000000").drawRect(262,383,10,10);
//		this.container.addChild(this.testShape);
		}

		/**
		 * 画图方法
		 * @param {Array} records 操作节点
		 */
		this.draw = function(records) {
			var success = false;
			async.each(records, function(obj, cb) {
				success = function(obj) {
					if(obj){
//						this.pushObj2Pages(obj);
						this.pushObj2UndoStack(obj);
					}
					cb();
				}.bind(this);

				this.handelRecords("normal", obj,success);

			}.bind(this), function(err) {
				this.container.update();
				if(err)
					console.error('err: ' + err);
			}.bind(this));
		}


		//绘制undo列表中的
		this._pringUndoList = function() {
			this.clearAllCanvas();
			var records = this.toolRedoUndo.undo_stack.get_stack();
			async.each(records, function(subRecords, cb) {
				async.each(subRecords,function(obj,callback){
					this.handelRecords("pringUndo",obj,callback);
				}.bind(this),function(err){
					cb();
				}.bind(this));
			}.bind(this), function(err) {
				this.container.update();
				if(err)
					console.error('err: ' + err);
			}.bind(this));
			
		}

		//清除所有轨迹
		this.clearAllCanvas = function() {
			this.container.removeAllChildren();
			this._pagers = [];
			this._currentPage = 0;
			this._pagers[0] = new Pager(this.canvasWidth,this.canvasHeight,this.pencilData);
			this._pagers[0].init();
			this.container.addChild(this._pagers[0].container);
		}

		/**
		 * records助手
		 * @param {String} handelType 助手类型（normal:正常解析/pringUndo:在undo列表中解析/）
		 * @param {obj} Object 要解析的对象
		 * @param {Function} success 成功的回调
		 */
		this.handelRecords = function(handelType, obj,success) {
			switch (obj.class) {
				case "DRContextRecord":
					var type = obj.type;
					switch (type) {
						case 1: //设置画笔颜色
							this.pencilData.setPainterColor(obj.data);
							success && success(obj);
							break;
						case 2: //设置画笔粗细
							this.pencilData.setPainterLineWidth(obj.data);
							success && success(obj);
							break;
						case 3: //设置混合模式（正常或者擦除）
							this.pencilData.setPainterMode(obj.data);
							success && success(obj);
							break;
						case 4: //插入空白页
							this.container.removeAllChildren();
							var mPager = new Pager(this.canvasWidth,this.canvasHeight,this.pencilData);
							mPager.init();
							this._pagers.splice(++this._currentPage, 0, mPager);
							this.container.addChild(this._pagers[this._currentPage].container);
							//保留对象
							if(obj.data == 0){
								this._pagers[this._currentPage].bgLayer.setBg(this._pagers[this._currentPage-1].bgLayer.getBg());
								this._pagers[this._currentPage].imgLayer.setImgs(this._pagers[this._currentPage-1].imgLayer.getImgs());
							}
							success(obj);
							break;
						case 5: //翻到下一页
							this.container.removeAllChildren();
							if(!this._pagers[++this._currentPage]){
								this._pagers[this._currentPage] = new Pager(this.canvasWidth,this.canvasHeight,this.pencilData);
								this._pagers[this._currentPage].init();
							}
							this.container.addChild(this._pagers[this._currentPage].container);
							success(obj);
							break;
						case 6: //幻灯片翻到上一页
							this.container.removeAllChildren();
							if(!this._pagers[--this._currentPage]){
								this._pagers[this._currentPage] = new Pager(this.canvasWidth,this.canvasHeight,this.pencilData);
								this._pagers[this._currentPage].init();
							}
							this.container.addChild(this._pagers[this._currentPage].container);
							success(obj);
							break;
						default:
							switch (handelType){
								case "normal":
									success(obj);
									break;
								default:
									success();
									break;
							}
				
							break;
					}
					break;
				case "DRStrokeRecord":
					this._pagers[this._currentPage].pencilDraw(obj,success);
					break;
				case "DRClearCanvasRecord":
					this._pagers[this._currentPage].clearPencil();
					success && success(obj);
					break;
				case "DRFileRecord":
					this.handleFile(obj);
					success && success(obj);
					break;
				case "DRRevokeRecord":
					switch (handelType){
						case "normal":
							this.emit('loading');
							this.toolRedoUndo.undo(obj, this._pringUndoList.bind(this), function(obj){
										success(obj);
										this.emit('loadover');
									}.bind(this) );
							break;
						default:
							success && success();
						break;
					}
					break;
				case "DRRedoRecord":
					switch (handelType){
						case "normal":
							this.toolRedoUndo.redo(obj, this._pringUndoList.bind(this), function(obj){
										success(obj);
									}.bind(this) );
							break;
						default:
							success && success();
						break;
					}
					break;
				default:
					success && success();
					break;
			}
		}

		//图片助手
		this.handleFile = function(obj) {
			var relativeSourcePath = obj.relativeSourcePath;
			var img = null;
			if (obj.fileType == 1) { //1是图片
				img = this.imgObj.img[relativeSourcePath];
				if (img.complete) {
					obj.imageObj = img;
					this._pagers[this._currentPage].drawImg(obj);
				} else
					console.error("读取图片失败！！");

			} else { //是文件或者ppt
				img = this.imgObj.fileOrPpt[relativeSourcePath];
				if (img.complete) {
					obj.imageObj = img;
					this._pagers[this._currentPage].drawBg(obj);
				} else
					console.error("读取文件或者ppt失败！！");
			}
		}
		
		//将轨迹加入到栈中
		this.pushObj2UndoStack = function(obj) {
            switch (obj.class){
            	case "DRStrokeRecord":
	            	this._tmpObj || ( this._tmpObj = [] );
	                this._tmpObj.push( obj );
	                if( obj.phase == "2" ){
	                    this.toolRedoUndo.undo_stack.push( this._tmpObj );
	                    this.toolRedoUndo.redo_stack.clear();
	                    this._tmpObj = void 0;
	                }
            		break;
            	case "DRContextRecord":
            		this._tmpObj || ( this._tmpObj = [] );
                    this._tmpObj.push( obj );
            		break;
            	case "DRFileRecord":
            	case "DRClearCanvasRecord":
	            	this._tmpObj || ( this._tmpObj = [] );
	                this._tmpObj.push( obj );
	                this.toolRedoUndo.undo_stack.push( this._tmpObj );
	                this.toolRedoUndo.redo_stack.clear();
	                this._tmpObj = void 0;
            	default:
            		break;
            }
		}



	};
	//继承事件
	util.inherits(Layer,EventEmitter);
	return Layer;
});